#! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on 2020/12/2 14:39 星期三

@author: jyz
"""

import os
import json
import requests
import hashlib
import time
from datetime import datetime

I_P = "https://test.whfciot.com"
appKey = "sDHYqAJjSF4e1nnzjan6Ua7s5eCaiPw7"
appSecret =  "iIT0r1148dNmjAzxExBN2JfzjHHQuy8j"


class getConfig:

    @staticmethod
    def get_camera_url():
        camera_paths, rtmp_urls = {}, {}

        url = I_P + '/fim/api/alg/device/list'
        r = requests.get(url)
        request_content = eval(r.text)['data']['list']
        src_stream_urls = [req['srcStreamUrl'] for req in request_content]  # rtsp://192.168.1.94:554/Streaming/Channels/101
        user_names = [req['username'] for req in request_content]
        passwords = [req['password'] for req in request_content]
        device_ids = [req['deviceId'] for req in request_content]
        src_push_urls = [req['srcPushUrl'] for req in request_content]  # 用于配置算法时显示原视频流
        camera_configs = [req['config'] for req in request_content]

        for srcStreamUrl, userName, password, dev_id, cc, src_push_url in zip(src_stream_urls, user_names, passwords, device_ids, camera_configs, src_push_urls):
            prefix_url = srcStreamUrl.split('//')[0]
            back_url = srcStreamUrl.split('//')[1]
            camera_paths[dev_id] = [prefix_url + '//' + userName + ':' + password + '@' + back_url +'?tcp',
                                    src_push_url]
            rtmp_url = {}
            for c in cc:
                if c['state'] != 0:
                    rtmp_url.setdefault(c['type'], c['pushUrl'])  # 获取每个算法的推流地址（rtmp)
            rtmp_urls[dev_id] = rtmp_url
        return camera_paths, rtmp_urls

    # 得到摄像头需要实现的功能,功能列表{安全帽：10，反光衣：20，越界：30，人员聚集：40，摔倒行为检测：50，人员离岗：60，人员徘徊：70，裸土覆盖：80，火焰检测：90}
    @staticmethod
    def get_camera_functions():
        device_configs = {}
        url = I_P + '/fim/api/alg/device/list'
        r = requests.get(url)
        if r.status_code == 200:
            # print('请求成功')
            pass
        while r.status_code != 200:
            print('请求失败，重新请求...')
            r = requests.get(url)
        request_content = eval(r.text)['data']['list']
        device_ids = [req['deviceId'] for req in request_content]
        camera_configs = [req['config'] for req in request_content]  # 摄像头关于各个算法的参数

        for d, c in zip(device_ids, camera_configs):
            valid_algos = [r for r in c if r["state"] != 0]
            device_configs.setdefault(d, {})
            for v in valid_algos:
                if 'timeList' in list(v.keys()):
                    device_configs[d][v["type"]] = {"rule": v["rule"], "timeList": [v["timeList"]]}
                else:
                    device_configs[d][v["type"]] = {"rule": v["rule"]}
                    pass
        return device_configs, device_ids




# 得到人脸以及抓拍图片保存本地保存地址，get请求，参数为空
def get_save_path():
    url = I_P + '/fim/api/alg/config'
    r = requests.get(url)
    print(json.dumps(eval(r.text)))
    request_content = eval(r.text)['data']

    faceImgPath = request_content['faceImgPath']
    resultImgPath = request_content['resultImgHttp']
    if os.path.exists(resultImgPath):
        pass
    else:
        resultImgPath = "."
    memory_usage = int(request_content['memoryUsage']) * 0.01  # 每个算法占用的显存比例
    out_stream_fps = int(request_content['outStreamFps'])  # 推流fps值
    capure_img_rate = int(request_content['captureImgRate'])  # 去重截图重复比例
    img_distinct_ratio = int(request_content['imgDistinctRatio'])  # 去重截图重复比例
    original_img_path = request_content['originalImgPath']

    return faceImgPath, resultImgPath, memory_usage, out_stream_fps, capure_img_rate, img_distinct_ratio, original_img_path


# 算法识别结果上传，post请求，参数为Content-Type,deviceId,type,time,files_path，值为multipart/form-data,设备号，
def upload_det_result(c_type, c_time, deviceId, img_name, result_path):
    url = I_P + '/fim/api/alg/result'
    image_path_ = result_path + '/' + img_name + '.jpg'
    device_payload = json.dumps({'deviceId': deviceId, 'type': c_type, 'time': c_time, 'resultImgPathList': [image_path_]})  # 前端要求resultImgPathList格式为list
    headers = {'Content-Type': 'application/json'}
    upload_result = requests.post(url, headers=headers, data=device_payload)
    assert upload_result.status_code == 200


def getTimestamp():
    return str(int(round(time.time() * 1000)))

def get_token():
    url = I_P + "/open/api/v1/auth/token"

    d = [
    ("appKey", appKey),
    ("randomStr", "0000111100001111"),
    ("timestamp", getTimestamp()),
    ]

    stringA = ""
    for key, value in d:
        stringA += key + "=" + value + "&"

    stringA += "appSecret=" + appSecret

    md5 = (hashlib.md5(stringA.encode('utf-8')).hexdigest()).upper()

    dd = {}
    for key, value in d:
        dd[key] = value
    dd["sign"] = md5

    headers = {'Content-Type': 'application/json'}
    try:
        r = requests.post(url, headers=headers, json = dd)
    except:
        print("failed to connect to cloud server.")
        return None
    # assert r.status_code == 200
    print(r.text)
    ans = eval(r.text)

    accessToken = ans["data"]["accessToken"]
    #print(accessToken)
    return accessToken

def  upload_detetion_result(fileFullPath):

    data = {
    "algDeviceId": "1",
    "deviceName": "fcwl",
    "type": "10",
    "typeName": "tired",
    "time": str(datetime.now()),
    }

    file = {
        "img": open(fileFullPath, 'rb')
    }
    accessToken = get_token()
    if accessToken is None:
        return
    papi = "/open/api/v1/fim/alg/result/upload?accessToken={0}".format(accessToken)
    url = I_P + papi
    try:
        r = requests.post(url, data= data, files = file)
        print(r.text)
    except:
        print("failed to upload img.")
        pass
    # assert r.status_code == 200


if __name__ == '__main__':
    ac = getConfig()
    # algorithm_type = '10'
    # c_time = '2020-01-08 09:39:23'
    # device_id = '1'
    ac.get_camera_url()
